package com.simple.weibo.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

import android.widget.*;
import com.simple.weibo.database.SimpleDatabase;
import com.simple.weibo.database.SimpleDatabaseHelper;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import com.simple.weibo.bean.User;
import com.simple.weibo.bean.Weibo;
import com.simple.weibo.oauth.OAuth;

public class WeiboMainActivity extends Activity implements View.OnClickListener {

    private List<Weibo> wbList = new ArrayList<Weibo>();
    private Map<String, SoftReference<Drawable>> cacheMap = new HashMap<String, SoftReference<Drawable>>();
    Handler handler;
    User user;

    ListView msglist;

    TextView userText;
    ImageButton wirteButton;
    ImageButton refreshButton;
    ViewFlipper flipper;

    ImageButton mainButton;
    ImageButton userButton;
    ImageButton infoButton;
    ImageButton aroundButton;

    int defCount = 20;
    ProgressDialog dialog;
    volatile boolean isGetting = false;

    boolean isMainInit;
    boolean isMsgInit;
    boolean isInfoInit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weibo_main_page);

        String userId = getIntent().getStringExtra("userId");
        if (userId != null) {
            SimpleDatabaseHelper helper = new SimpleDatabaseHelper(this, "mydatabase", null, 1);
            SimpleDatabase sd = new SimpleDatabase(helper);
            user = sd.getUserById(userId);
            sd.close();
        }

        if (user != null) {

            dialog = new ProgressDialog(this);
            dialog.setTitle("请稍等");
            dialog.setMessage("获取微博中...");
            dialog.show();
            findViews();
            setViews();

            new Thread(new Runnable() {
                public void run() {
                    isGetting = true;
                    try {
                        loadList(user, defCount, 0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (user.getUserName() == null) {
                        getUserInfo();
                    }
                }
            }).start();

            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 0) {
                        isGetting = false;
                        ((WeiboAdapater) msglist.getAdapter()).notifyDataSetChanged();
                        dialog.dismiss();
                    } else if (msg.what == 1) {
                        isGetting = false;
                        ((WeiboAdapater) msglist.getAdapter()).notifyDataSetChanged();
                        dialog.dismiss();
                    } else if (msg.what == 2) {
                        userText.setText(user.getUserName());
                    }
                    super.handleMessage(msg);
                }
            };
        } else {
            startActivity(new Intent(this, MainActivity.class));
        }
    }

    private void findViews() {

        userText = (TextView) findViewById(R.id.user_text);
        wirteButton = (ImageButton) findViewById(R.id.write_weibo);
        refreshButton = (ImageButton) findViewById(R.id.refresh_weibo);
        flipper = (ViewFlipper) findViewById(R.id.flipper);

        mainButton = (ImageButton) findViewById(R.id.mainButton);
        userButton = (ImageButton) findViewById(R.id.msgButton);
        infoButton = (ImageButton) findViewById(R.id.infoButton);
        aroundButton = (ImageButton) findViewById(R.id.aroundButton);

    }

    private void setViews() {
        View main = LayoutInflater.from(this).inflate(R.layout.weibo_main, null);
        View msg = LayoutInflater.from(this).inflate(R.layout.weibo_msg, null);
        flipper.addView(main, 0);
        flipper.addView(msg, 1);

        flipper.setDisplayedChild(0);
        userText.setText(user.getUserName());
        setMainPage();

        mainButton.setOnClickListener(this);
        userButton.setOnClickListener(this);
        infoButton.setOnClickListener(this);
        aroundButton.setOnClickListener(this);
    }

    //微博主页面
    private void setMainPage() {
        isMainInit = true;
        msglist = (ListView) findViewById(R.id.weiboList);
        msglist.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
                Object obj = view.getTag();
                if (obj != null) {
                    String id = obj.toString();
                    Intent intent = new Intent(WeiboMainActivity.this, WeiboContextActivity.class);
                    Bundle b = new Bundle();
                    b.putString("id", id);
                    b.putString("userId", user.getUserId());

                    intent.putExtras(b);
                    startActivity(intent);
                }
            }
        });
        msglist.setOnScrollListener(new OnScrollListener() {
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                int count = firstVisibleItem + visibleItemCount;
                if (count != 0 && count == totalItemCount && !isGetting) {
                    isGetting = true;
                    dialog.show();
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                defCount += 20;
                                loadList(user, defCount, 0);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            }
        });

        WeiboAdapater adapater = new WeiboAdapater(wbList);
        msglist.setAdapter(adapater);
        refreshButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dialog.show();
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            loadList(user, defCount, 1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }

    //得到用户名和头像图片
    private void getUserInfo() {

        OAuth oauth = new OAuth();
        String url = "http://api.t.sina.com.cn/users/show.json";
        List<NameValuePair> pairList = new ArrayList<NameValuePair>();
        pairList.add(new BasicNameValuePair("source", OAuth.appKey));
        pairList.add(new BasicNameValuePair("user_id", user.getUserId()));
        HttpResponse response = oauth.getServerResponse(user.getAccessToken(), user.getAccessTokenSecret(), url, pairList);
        BufferedReader br;
        try {
            br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuilder sb = new StringBuilder();
            String str = "";
            while ((str = br.readLine()) != null) {
                sb.append(str).append("\r\n");
            }
            String sg = sb.toString();
            System.out.println(sg);
            try {
                JSONObject o = new JSONObject(sg);
                user.setUserName(o.getString("screen_name"));
                Drawable dw = Drawable.createFromStream(new URL(o.getString("profile_image_url")).openStream(), "image");
                user.setIcon(dw);
                SimpleDatabase sd = new SimpleDatabase(new SimpleDatabaseHelper(this, "mydatabase", null, 1));
                sd.updateInfo(user);
                sd.close();
                handler.sendEmptyMessage(2);
            } catch (JSONException e) {
                e.printStackTrace();
            }


        } catch (IllegalStateException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

    //获得用户关注的最新微博
    private void loadList(User user, int count, int what) {

        OAuth oauth = new OAuth();
        String url = "http://api.t.sina.com.cn/statuses/friends_timeline.json";
        List<NameValuePair> pairList = new ArrayList<NameValuePair>();
        pairList.add(new BasicNameValuePair("source", OAuth.appKey));
        pairList.add(new BasicNameValuePair("count", String.valueOf(count)));
        HttpResponse response = oauth.getServerResponse(user.getAccessToken(), user.getAccessTokenSecret(), url, pairList);
        if (response.getStatusLine().getStatusCode() == 200) {

            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuilder sb = new StringBuilder();
                String str = "";
                while ((str = br.readLine()) != null) {
                    System.out.println(str);
                    sb.append(str).append("\r\n");
                }
                String sg = sb.toString();
                JSONArray data = new JSONArray(sg);
                wbList.clear();
                for (int i = 0; i < data.length(); i++) {
                    JSONObject d = data.getJSONObject(i);
                    if (d != null) {
                        JSONObject u = d.getJSONObject("user");

                        //微博id
                        String id = d.getString("id");
                        String userId = u.getString("id");
                        String userName = u.getString("screen_name");
                        String userIcon = u.getString("profile_image_url");

                        String time = d.getString("created_at");
                        Date date = new Date(time);
                        time = new SimpleDateFormat("MM-dd HH:mm:ss").format(date);
                        String text = d.getString("text");
                        Boolean haveImg = false;
                        if (d.has("thumbnail_pic")) {
                            haveImg = true;
                        }
                        if (d.has("retweeted_status")) {
                            JSONObject r = d.getJSONObject("retweeted_status");
                            text += "\r\n$";
                            JSONObject uu = r.getJSONObject("user");

                            text += uu.getString("screen_name") + ":" + r.getString("text") + "$";
                        }
                        Weibo w = new Weibo();
                        w.setId(id);
                        w.setUserId(userId);
                        w.setUserName(userName);

                        w.setTime(time);
                        w.setText(text);

                        w.setHaveImage(haveImg);
                        w.setUserIcon(userIcon);
                        wbList.add(w);
                    }
                }
            } catch (IllegalStateException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            } catch (JSONException e) {

                e.printStackTrace();
            }

        }

        handler.sendEmptyMessage(what);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mainButton:
                flipper.setDisplayedChild(0);
                if (!isMainInit) {
                    setMainPage();
                }
                break;
            case R.id.msgButton:
                flipper.setDisplayedChild(1);
                if (!isMsgInit) {
                    System.out.println(user.getIcon());
                    MainPageUtils.setMessagePage(dialog, this, user, refreshButton);
                    isMsgInit = true;
                }
                break;
            case R.id.infoButton:
                break;
            case R.id.aroundButton:
                break;
        }
    }

    class WeiboAdapater extends BaseAdapter {

        Handler imageHandler;
        List<Weibo> list = new ArrayList<Weibo>();

        public WeiboAdapater(List<Weibo> list) {
            imageHandler = new Handler() {

                @Override
                public void handleMessage(Message msg) {
                    try {
                        ImageView wbimage = (ImageView) (msglist.getChildAt(msg.arg1)).findViewById(R.id.wbicon);
                        wbimage.setImageDrawable((Drawable) msg.obj);
                        wbimage.invalidate();
                    } catch (Exception e) {
                    }
                    super.handleMessage(msg);
                }

            };
            this.list = list;
        }


        public int getCount() {
            return list.size();
        }


        public Object getItem(int position) {
            return list.get(position);
        }


        public long getItemId(int position) {
            return position;
        }


        public View getView(int position, View convertView, ViewGroup parent) {
            final int pos = position;

            if (convertView == null) {
                convertView = LayoutInflater.from(WeiboMainActivity.this).inflate(R.layout.weibo_content, null);
            }

            ImageView wbicon = (ImageView) convertView.findViewById(R.id.wbicon);
            TextView wbtext = (TextView) convertView.findViewById(R.id.wbtext);
            TextView wbtime = (TextView) convertView.findViewById(R.id.wbtime);
            TextView wbuser = (TextView) convertView.findViewById(R.id.wbuser);
            ImageView wbimage = (ImageView) convertView.findViewById(R.id.wbimage);

            final Weibo wb = list.get(position);

            convertView.setTag(wb.getId());
            wbuser.setText(wb.getUserName());
            wbtime.setText(wb.getTime());
            wbtext.setText(wb.getText(), TextView.BufferType.SPANNABLE);
            MainPageUtils.highLightTex(wbtext, "#", "#");
            MainPageUtils.highLightTex(wbtext, "@", ":");
            MainPageUtils.highLightTex(wbtext, "@", " ");
            MainPageUtils.highLightTex(wbtext, "http://", " ");
            MainPageUtils.highLightTex2(wbtext, "$", "$");

            if (wb.getHaveImage()) {
                wbimage.setImageResource(R.drawable.t_sina);
            }
            Drawable image = null;
            try {
                image = cacheMap.get(wb.getUserIcon()).get();
            } catch (Exception e) {
            }
            if (image == null) {
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            Drawable draw = Drawable.createFromStream(new URL(wb.getUserIcon()).openStream(), "image");
                            SoftReference<Drawable> soft = new SoftReference<Drawable>(draw);
                            cacheMap.put(wb.getUserIcon(), soft);
                            Message msg = imageHandler.obtainMessage();
                            msg.arg1 = pos;
                            msg.obj = draw;
                            imageHandler.sendMessage(msg);
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                }).start();
                wbicon.setImageResource(R.drawable.icon);
            } else {
                wbicon.setImageDrawable(image);
            }
            return convertView;
        }

    }
}